<template>
	<s-layout navbar="inner1" :bgStyle="{
		color:'#F6F6F6'
	}">
	<z-paging ref="paging" v-model="currentMessageList" use-chat-record-mode safe-area-inset-bottom
		bottom-bg-color="#f8f8f8" @query="queryList" @keyboardHeightChange="keyboardHeightChange"
		@hidedKeyboard="hidedKeyboard">
		<template #top>
			<assNavbar :title="title" :maxLength="9">
				<template #left>
				</template>
				<template #right v-if="!isSystem">
					<view class="ss-flex-1 ss-flex justify-end">
						<image class="more-info" @click="personalClick"
							src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/mengchong/more.png"
							mode="aspectFit">
						</image>
					</view>
				</template>
			</assNavbar>
		</template>
		<Friend></Friend>
		<view class="chat ss-p-t-30 ss-p-x-20">
			<!-- 系统通知 -->
			<view v-if="isSystem">
				<view style="transform: scaleY(-1);" v-for="(message, index) in currentMessageList" :key="message.id">
					<view class="message-time">{{ TimeString(message.timeString) }}</view>
					<Wallet :message="message" v-if="message.type === 'TIMCustomElem' && message.userID === 'wallet'">
					</Wallet>
					<Order :message="message"
						v-else-if="message.type === 'TIMCustomElem' && message.userID === 'order'"></Order>
					<System :message="message"
						v-else-if="message.type === 'TIMCustomElem' && message.userID === 'system'"></System>
				</view>
			</view>
			<!-- 聊天 -->
			<view v-else>
				<view style="transform: scaleY(-1);" v-for="(message, index) in currentMessageList" :key="index">
					<view class="message-time">{{ TimeString(message.timeString) }}</view>
					<!-- 聊天消息 -->
					<view :class="(message.flow === 'out') ? 'item-right' : 'item-left'">
						<view :class="[message.flow === 'out' ? 'ss-m-r-20' : 'ss-m-l-20']">
							<view class="name">
								{{ message.nick }}
							</view>
							<view class="content">
								<view class="read-receipts"
									v-if="message.conversationType === 'C2C' && message.status === 'success'">
									<view v-if="message.isPeerRead">已读</view>
									<view v-else>未读</view>
								</view>
								<!-- 文本消息 -->
								<TextMessage :message="message" v-if="message.type === 'TIMTextElem'"></TextMessage>
								<!-- 图片消息 -->
								<ImageMessage :message="message" v-if="message.type === 'TIMImageElem'"></ImageMessage>
								<!-- 视频消息 -->
								<VideoMessage :message="message" v-if="message.type === 'TIMVideoFileElem'"></VideoMessage>
								<!-- 自定义消息 -->
								<GoodsMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'goods'"></GoodsMessage>
								<ActivityMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'activity'"></ActivityMessage>
								<GroupMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'group'"></GroupMessage>
								<RedMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'red'"></RedMessage>
								<CouponMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'coupon'"></CouponMessage>
								<ConfirmMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'share_order'"></ConfirmMessage>
								<FindMessage :message="message" v-if="message.payload.type === 'TIMCustomElem' && message.payload.custom.type === 'find'"></FindMessage>
							</view>
						</view>
						<view class="user-avatar">
							<image :src="cdn(message.avatar) || 'http://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/static/img/default_avatar.png'" mode="aspectFill" />
						</view>
					</view>
				</view>
				<view class="apply-box" v-if="isFriend"></view>
			</view>
		</view>
		<template #bottom>
			<view class="bottom" v-if="!isSystem">
				<view class="bottom-div">
					<view class="w-100">
						<input class="input" :adjust-position="false" v-model.lazy:value="messageContent" confirm-type="send" cursor-spacing="10"
							:focus="isFocus" @focus="isFocusSet" @blur="isFocus = false" @confirm="sendMessage" />
					</view>

					<view class="btn" @click="handleEmoji">
						<image class="emoji-tab-open"
							src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/tx_im/smile.png" mode="" />
					</view>
					<view class="send" @click="sendMessage" v-if="messageContent.length !== 0">
						发送
					</view>
					<view class="btn" @click="handleMore" v-else>
						<image style="width:50rpx;height:50rpx"
							src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/tx_im/more.png" mode="" />
					</view>
				</view>
				<!--    更多部分-->
				<view class="bottom-image" v-if="isMoreOpen">
					<view class="images">
						<view class="block" @click="sendPhoto">
							<view class="image">
								<image src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/tx_im/picture.png"
									class="icon" />
							</view>
							<view class="name">
								图片
							</view>
						</view>
						<view class="block" @click="video">
							<view class="image">
								<image src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/tx_im/video-file.png"
									class="icon" />
							</view>
							<view class="name">
								视频
							</view>
						</view>
					</view>
				</view>
				<!-- emoji部分 表情 -->
				<view class="bottom-emoji" v-if="isEmojiOpen">
					<view class="emoji-tab">
						<view class="tabs">
							<view class="single" @click="handleEmojiShow" :class="emojiShow ? 'choosed' : ''">
								<image src="https://liuliangbenben.oss-cn-hangzhou.aliyuncs.com/tx_im/smile.png"
									style="width:100%;height:100%"></image>
							</view>
						</view>
					</view>
					<view class="emojis" v-if="emojiShow">
						<view v-for="(emojiItem, index3) in emojiName" class="emoji" :key="index3"
							@click="chooseEmoji(emojiItem)">
							<image :src="emojiUrl + emojiMap[emojiItem]" style="width:100%;height:100%" />
						</view>
					</view>
				</view>
			</view>
		</template>
	</z-paging>
	</s-layout>
</template>

<script setup>
	import {
		ref,
		computed,
		reactive
	} from 'vue';
	import {
		onLoad,
		onUnload,
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import {
		emojiName,
		emojiMap,
		emojiUrl
	} from '@/im/store/im/emojiMap.js'
	import assNavbar from '@/im/components/ass-navbar.vue'
	import Friend from '@/im/components/message/friend.vue'
	import Order from '@/im/components/message/order.vue'
	import System from '@/im/components/message/system.vue'
	import Wallet from '@/im/components/message/wallet.vue'
	import TextMessage from '@/im/components/message/textMessage.vue'
	import ImageMessage from '@/im/components/message/imageMessage.vue'
	import VideoMessage from '@/im/components/message/videoMessage.vue'
	import GoodsMessage from '@/im/components/message/goodsMessage.vue'
	import ActivityMessage from '@/im/components/message/activityMessage.vue'
	import GroupMessage from '@/im/components/message/groupMessage.vue'
	import RedMessage from '@/im/components/message/redMessage.vue'
	import CouponMessage from '@/im/components/message/couponMessage.vue'
	import ConfirmMessage from '@/im/components/message/ConfirmMessage.vue'
	import FindMessage from '@/im/components/message/findMessage.vue'
	import $store from '@/im/store/im';
	import imApi from '@/im/api/index.js'
	import {
		cdn,
		udid
	} from '@/im/config/index.js'

	const paging = ref(null)

	const title = ref('')
	const isEmojiOpen = ref(false)
	const isMoreOpen = ref(false)
	const messageContent = ref('')
	const isFocus = ref(false)
	const emojiShow = ref(true)

	// 是否是好友
	const isFriend = computed(() => $store().isFriend)
	const isSystem = computed(() => $store().isSystem)
	const isReady = computed(() => $store().isReady)
	const currentMessageList = computed(() => $store().chatMessageList);
	const chatInfo = computed(() => $store().chatInfo);
	const iMMyInfo = computed(() => $store().userInfo);
	const chatListHeight = computed(() => {
		if (isSystem.value) {
			return sheep.$platform.device.screenHeight - ($store().statusBarHeight ? $store()
				.statusBarHeight : 0) - 44 - sheep.$platform.device.statusBarHeight - 44
		}
		return sheep.$platform.device.screenHeight - ($store().statusBarHeight ? $store()
			.statusBarHeight : 0) - 44 - 44 - 70 - (isEmojiOpen.value ? 180 : 0) - (isMoreOpen.value ? 100 : 0)
	})
	const seatListHeight = computed(() => {
		return 70 + (isEmojiOpen.value ? 180 : 0) + (isMoreOpen.value ? 100 : 0)
	})

	onLoad(async (options) => {
		if (options.title) {
			title.value = options.title
		}
	});


	const isMessage = () => {
		if (currentMessageList.value.length >= 1) {
			return currentMessageList.value.filter(item => {
				return item.to === iMMyInfo.value.userID
			})
		}
		return []
	}

	//发送消息
	function sendMessage() {
		let messageVal = messageContent.value
		let urlList = extractLinkUrls(messageVal)
		if (urlList.length > 0) {
			urlList.forEach((item) => {
				if (messageVal.includes(item)) {
					let urla = "<a href=" + item + ">" + item + "</a>";
					let regex = /(<a\b[^>]*>.*?<\/a>)|https?:\/\/\S+/g;
					messageContent.value = messageVal.replace(regex, (match) => {
						if (match.startsWith("<a")) {
							// 如果匹配到的部分是 <a> 标签，则返回原始内容，不执行替换
							return match;
						} else {
							// 如果是链接地址，执行替换操作
							return urla;
						}
					});
				}
			})
		}
		if (!isnull(messageContent.value)) {
			if (isMessage().length >= 3 && isFriend.value) {
				uni.showToast({
					title: '非好友最多发送三条信息，添加为好友不受限制哦！',
					icon: 'none'
				})
				return
			}
			uni.showLoading({
				title: '发送消息中'
			});
			let message = wx.$app.createTextMessage({
				to: chatInfo.value.userProfile.userID,
				conversationType: wx.TIM.TYPES.CONV_C2C,
				payload: {
					text: messageContent.value
				}
			})
			wx.$app.sendMessage(message).then(res => {
				uni.hideLoading();
				$store().pushChatMessageList(message)
				paging.value.addChatRecordData()
			}).catch(err => {
				console.log(err)
				uni.hideLoading();
				uni.showToast({
					title: '消息发送失败!请稍后再试' + err,
					duration: 1500,
					icon: 'none'
				});
			})
			messageContent.value = ''
		} else {
			uni.showToast({
				title: '消息不能为空',
				icon: 'none'
			})
		}
		handleClose()
	};

	function isnull(content) {
		if (content === '') {
			return true
		}
		const reg = '^[ ]+$'
		const re = new RegExp(reg)
		return re.test(content)
	};

	function extractLinkUrls(text) {
		const regex = /(https?:\/\/[^\s]+)/g; // 匹配链接地址的正则表达式
		const matches = text.match(regex);
		if (matches) {
			return matches;
		}
		return [];
	};

	// 发送图片
	function sendPhoto() {
		if (isReady.value) {
			chooseImage()
		}
	};

	function chooseImage() {
		let self = this
		let message = {}
		if (isMessage().length >= 3 && isFriend.value) {
			uni.showToast({
				title: '非好友最多发送三条信息，添加为好友不受限制哦！',
				icon: 'none'
			})
			return
		}
		uni.chooseImage({
			sourceType: ['album', 'camera'],
			count: 1,
			success(res) {
				uni.showLoading({
					title: '发送图片中'
				});
				message = wx.$app.createImageMessage({
					to: chatInfo.value.userProfile.userID,
					conversationType: wx.TIM.TYPES.CONV_C2C,
					payload: {
						file: res
					},
					onProgress(event) {
						console.log('file uploading:', event)
					}
				})
				wx.$app.sendMessage(message).then(res => {
					uni.hideLoading();
					$store().pushChatMessageList(message)
					paging.value.addChatRecordData()
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: '消息发送失败!请稍后再试',
						duration: 1500,
						icon: 'none'
					});
				})
				handleClose()
			},
			fail: (err) => {
				console.log(err)
			}
		})

	}

	// 发送视频消息
	function video() {
		if (isMessage().length >= 3 && isFriend.value) {
			uni.showToast({
				title: '非好友最多发送三条信息，添加为好友不受限制哦！',
				icon: 'none'
			})
			return
		}
		wx.chooseVideo({
			sourceType: ['album', 'camera'],
			maxDuration: 60,
			camera: 'back',
			success(res) {
				uni.showLoading({
					title: '发送视频中'
				});
				let message = wx.$app.createVideoMessage({
					to: chatInfo.value.userProfile.userID,
					conversationType: wx.TIM.TYPES.CONV_C2C,
					payload: {
						file: res
					},
					onProgress: function(event) {
						console.log('file uploading:', event)
					}
				})

				wx.$app.sendMessage(message).then(res => {
					uni.hideLoading();
					$store().pushChatMessageList(message)
					paging.value.addChatRecordData()
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: '消息发送失败!请稍后再试',
						duration: 1500,
						icon: 'none'
					});
				})
				handleClose()
			}
		})
	};

	// 发消息选中emoji
	function chooseEmoji(item) {
		messageContent.value += item
	};

	function personalClick() {
		if (isSystem.value) {
			return
		}
		uni.navigateTo({
			url: '/im/pages/userInfo?type=chat'
		})
	};

	function queryList(pageNo, pageSize) {
		$store().getChatMessageList(pageNo).then(res => {
			paging.value.complete(res);
			$store().unshiftMessageList(res)
		})
	}

	function hidedKeyboard() {

	}

	function keyboardHeightChange() {

	}

	function handleClose() {
		isFocus.value = false
		isEmojiOpen.value = false
		isMoreOpen.value = false
	}

	// 展示
	function handleMore() {
		isFocus.value = false
		isEmojiOpen.value = false
		isMoreOpen.value = true
	};

	// 展示
	function handleEmoji() {
		if (isFocus.value) {
			isFocus.value = false
			isMoreOpen.value = false
			isEmojiOpen.value = true
		} else {
			isEmojiOpen.value = !isEmojiOpen.value
			isMoreOpen.value = false
		}
	};

	// 展示
	function handleEmojiShow() {
		emojiShow.value = true
	};

	// 展示
	function isFocusSet() {
		isEmojiOpen.value = false
		isMoreOpen.value = false
		isFocus.value = true
		if (sheep.$platform.os.toLowerCase() !== "ios") {
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999,
				})
			}, 150)
		}
	}

	// 处理时间格式
	const TimeString = (time) => {
		let newTime = time.replace(/\//g, '-')
		const dateTime = new Date(newTime.replace(' ', 'T'));
		const timestamp = dateTime.getTime() / 1000; // 转换为秒级时间戳
		return sheep.$helper.timeFrom(timestamp)
	}
</script>

<style lang="scss" scoped>
	::v-deep {
		.z-paging-content-full {
			bottom: 1px !important;
		}
	}

	view {
		box-sizing: border-box;
	}

	.more-info {
		width: 60rpx;
		height: 50rpx;
		margin-top: 12rpx;
	}

	.user-avatar {
		image {
			width: 68rpx;
			height: 68rpx;
			border-radius: 50%;
		}
	}

	.bottom {
		background-color: #ededed;
		width: 100%;
		padding-bottom: 25px;
	}

	.bottom-div {
		width: 100%;
		display: flex;
		align-items: center;

		border-top: 1px solid #dddddd;
		padding: 10px;
		padding-bottom: 0;
		flex-direction: row;
		box-sizing: border-box;
		transition: all 0.3s;

		.send {
			font-size: 14px;
			background-color: #EF932E;
			color: white;
			border-radius: 4px;
			width: 80px;
			height: fit-content;
			padding: 6px;
			margin-left: 6px;
			text-align: center;
		}
	}

	.bottom-emoji {
		position: relative;

		.emojis {
			height: 150px;
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			overflow-y: scroll;
			box-sizing: border-box;

			.emoji {
				height: 12.5vw;
				width: 12.5vw;
				padding: 8px;
				box-sizing: border-box;
			}

			.bigemoji {
				height: 20vw;
				width: 20vw;
				padding: 10px;
				box-sizing: border-box;
			}
		}
	}

	.emoji-tab {
		box-sizing: border-box;
		border-bottom: 1px solid #dbdbdb;

		.tabs {
			display: flex;
			// height: 29px;
			flex-direction: row;
			padding-left: 10px;
			box-sizing: border-box;

			.single {
				display: flex;
				width: 26px;
				height: 26px;
				padding: 2px;
				border-radius: 6px;
				box-sizing: border-box;
				margin: 5px 0;
			}

			.choosed {
				background-color: rgba(255, 255, 255, 0.7);
			}
		}
	}

	.bottom-image {
		box-sizing: border-box;

		.images {
			box-sizing: border-box;
			display: flex;
			padding: 0 12px;
			margin-top: 16px;

			&:last-child {
				margin-bottom: 16px;
			}

			.block {
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin: 0 12px;

				.name {
					margin-top: 6px;
					font-size: 12px;
					color: #999999;
					text-align: center;
				}

				.image {
					width: 50px;
					height: 50px;
					display: flex;
					justify-content: center;
					align-items: center;
					box-sizing: border-box;
					border-radius: 8px;
					background-color: white;
					padding: 3vw;
				}

				.icon {
					width: 26px;
					height: 26px;
				}
			}
		}
	}

	.input {
		width: 100%;
		background-color: white;
		border-radius: 6px;
		height: 34px;
		box-sizing: border-box;
		padding: 0 8px;
	}

	.btn-left {
		display: flex;
		padding: 0;
		margin: 0;
		margin-right: 10px;
	}

	.btn {
		display: flex;
		padding: 0;
		margin: 0;
		margin-left: 10px;
	}

	.item-right {
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
		margin-bottom: 20rpx;
		
		.content {
			display: flex;
			align-items: center;
		}

		.name {
			font-size: 24rpx;
			margin-bottom: 12rpx;
			color: #666666;
			text-align: right;
		}
		
		.read-receipts {
			color: #666666;
			font-size: 24rpx;
			margin-right: 20rpx;
		}
	}


	.item-left {
		display: flex;
		flex-direction: row-reverse;
		justify-content: flex-end;
		margin-bottom: 20rpx;
		
		.content {
			display: flex;
			flex-direction: row-reverse;
			align-items: center;
		}

		.name {
			font-size: 24rpx;
			margin-bottom: 12rpx;
			color: #666666;
			text-align: left;
		}
		
		.read-receipts {
			color: #666666;
			font-size: 24rpx;
			margin-left: 20rpx;
		}
	}
	
	.message-time {
		text-align: center;
		padding: 20rpx 0;
		opacity: 0.4;
	}



	.apply-box {
		width: 100%;
		height: 120rpx;
	}
	
	
	.emoji-tab-open {
		width:50rpx;
		height:50rpx;
		margin-left: 20rpx;
	}
</style>